package com.box1312.fishpond;

public enum Utils {

  INSTANCE;

  public byte[] intToByte(int value) {
    return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value };
  }

  public int byteToInt(byte[] bytes) {
    return byteToInt(bytes[0], bytes[1], bytes[2], bytes[3]);
  }

  public int byteToInt(byte b1, byte b2, byte b3, byte b4) {
    return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF);
  }

  public byte[] longToBytes(long val) {
    byte[] b = new byte[8];
    for (int i = 7; i > 0; i--) {
      b[i] = (byte) val;
      val >>>= 8;
    }
    b[0] = (byte) val;
    return b;
  }

  public long byteToLong(byte[] bytes) {
    long l = 0;
    for (int i = 0; i < Long.SIZE / Byte.SIZE; i++) {
      l <<= 8;
      l ^= bytes[i] & 0xFF;
    }
    return l;
  }

  public int hash(Object k) {
    int h = 131313;

    if ((0 != h) && (k instanceof String)) {
      return sun.misc.Hashing.stringHash32((String) k);
    }

    h ^= k.hashCode();

    // Spread bits to regularize both segment and index locations,
    // using variant of single-word Wang/Jenkins hash.
    h += (h << 15) ^ 0xffffcd7d;
    h ^= (h >>> 10);
    h += (h << 3);
    h ^= (h >>> 6);
    h += (h << 2) + (h << 14);
    return h ^ (h >>> 16);
  }

  public byte[] hashKeyEncode(String key, String field) {
    String hk = "_" + key + "_" + field;
    return intToByte(hash(hk));
  }
}
